// ignore_for_file: use_build_context_synchronously

import 'dart:async';
import 'dart:convert';
import 'dart:io';

import 'package:coordtransform/coordtransform.dart';
import 'package:flutter/material.dart';
import 'package:flutter/src/widgets/visibility.dart' as visibility;
import 'package:flutter_native_screenshot/flutter_native_screenshot.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:htxd_flutter_mapbox_sdk/entity/back_home.dart';
import 'package:htxd_flutter_mapbox_sdk/htxd_flutter_mapbox_sdk.dart';
import 'package:mapbox_maps_flutter/mapbox_maps_flutter.dart';
import 'package:path_provider/path_provider.dart';

import '../dialog/land_draw_quit_dialog.dart';
import '../dialog/land_info_complete_dialog.dart';
import '../dialog/land_operate_dialog.dart';
import '../dialog/village_land_info_dialog.dart';
import '../entity/select_entity.dart';
import '../mapbox/util/number_util.dart';
import '../search/amap_search.dart';
import '../search/search_poi_entity.dart';
import '../util/event_bus_util.dart';
import '../util/image_clip/image_clip_util.dart';

typedef Result = Function();

/// 地块勾画界面
class DrawLandPage extends StatelessWidget {
  Map<String, dynamic> data;

  DrawLandPage({Key? key, required this.data}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return WillPopScope(
        child: Scaffold(
          resizeToAvoidBottomInset: false,
          backgroundColor: Colors.white,
          appBar: AppBar(
            leading: IconButton(
              onPressed: () {
                EventBusUtil.fire(BackEntity());
              },
              icon: const Icon(
                Icons.arrow_back_ios,
                color: Colors.black,
              ),
            ),
            backgroundColor: Colors.white,
            shadowColor: Colors.transparent,
            title: Text(
              '绘制地块',
              style: TextStyle(fontSize: 16.sp, color: Colors.black),
            ),
            centerTitle: true,
          ),
          body: DrawLandPageContent(
            data: data,
          ),
        ),
        onWillPop: () async {
          return false;
        });
  }
}

class DrawLandPageContent extends StatefulWidget {
  Map<String, dynamic> data;

  DrawLandPageContent({Key? key, required this.data}) : super(key: key);

  @override
  State<DrawLandPageContent> createState() => _DrawLandPageContentState();
}

class _DrawLandPageContentState extends State<DrawLandPageContent> {
  DrawLandManager? _drawLandManager;
  MapBoxControl? _mapBoxControl;
  late AmapLocationControl _amapLocationControl;
  late TextEditingController _textEditingController;

  // 3千米距离限制
  final String _3K_BUFFER_SOURCE = "3k_buffer_source";
  final String _3K_BUFFER_LAYER = "3k_buffer_layer";

  // 所有的地块
  final String _ALL_LAND_SOURCE = "all_land_source";
  final String _ALL_LAND_LINE_LAYER = "all_land_line_layer";
  final String _ALL_LAND_FILL_LAYER = "all_land_fill_layer";
  final String _ALL_LAND_CENTER_SOURCE = "all_land_center_source";
  final String _ALL_LAND_CENTER_LAYER = "all_land_center_layer";

  // 四至部分
  final String _LAND_FOUR_LINE_SOURCE = "land_four_line_source";
  final String _LAND_FOUR_LINE_LAYER = "land_four_line_layer";

  final String _LAND_FOUR_POINT_SOURCE = "land_four_point_source";
  final String _LAND_FOUR_POINT_LAYER = "land_four_point_layer";

  // 该村的地块
  final String _VILLAGE_LAND_FILL_SOURCE = "village_land_fill_source";
  final String _VILLAGE_LAND_FILL_LAYER = "village_land_fill_layer";
  final String _VILLAGE_LAND_LINE_LAYER = "village_land_line_layer";

  // 覆盖率部分
  final String _OVERLAP_SOURCE = "overlap_source";
  final String _OVERLAP_LINE_LAYER = "overlap_line_layer";
  final String _OVERLAP_FILL_LAYER = "overlap_fill_layer";
  final String _OVERLAP_CENTER_SOURCE = "overlap_center_source";
  final String _OVERLAP_CENTER_LAYER = "overlap_center_layer";

  // 截图部分
  final String _SNAPSHOT_LAND_SOURCE = "snapshot_land_source";
  final String _SNAPHOT_LAND_FILL_LAYER = "snapshot_land_fill_layer";
  final String _SNAPHOT_LAND_LINE_LAYER = "snapshot_land_line_layer";

  // poi 相关
  final List<SearchPoiEntity> _poiList = [];
  bool _isShowPoiSearch = false;

  // 图层控制相关
  bool _isShowSwitchLayers = false;
  final List<LayerNameEntity> _layerNames = [];

  // 控制地块的筛选
  bool _isSwitchLand = false;

  // 是否显示四至点
  bool _isShowFour = false;

  // 是否开始勾画
  bool _isStartDraw = false;

  // 是否限制覆盖率
  bool _isShowOverlap = false;

  // 是否显示操作盘
  bool _isShowControl = false;

  // 是否开始截屏
  bool _isScreenshot = false;

  final List<LandInfoEntity> _allLands = [];
  final List<VillageLandEntity> _allVillageLands = [];

  String _confirmationName = "";
  String _confirmationIdCard = "";
  String _provinceCode = "";

  // 编辑操作的地块
  LandInfoEntity? _landInfoEntity;

  // 能够参与计算的地块
  final List<VillageLandEntity> _canCalVillageLands = [];
  final List<SelectEntity> _yearListSelect = [];
  final List<SelectEntity> _cropListSelect = [];

  late StreamSubscription<BackEntity> _subscription;

  // 在保存地块
  bool _isSaveLand = false;

  // 任务类型
  TaskType? _taskType;

  int lastTime = 0;

  late bool directDraw;
  @override
  void initState() {
    super.initState();
    directDraw = widget.data['directDraw'] == 'true';
    DrawLandWebSocketListener.websocket_userId =
        "${widget.data['websocket_userId']}";
    DrawLandWebSocketListener.websocket_sessionId =
        "${widget.data['websocket_sessionId']}";
    DrawLandWebSocketListener.websocket_staffuserId =
        "${widget.data['websocket_staffuserId']}";

    _amapLocationControl = AmapLocationControl(locationSuccess: (locationBean) {
      _add3KilometersCircle(locationBean.position!);
    });
    _amapLocationControl.startLocation();
    _textEditingController = TextEditingController();
    _textEditingController.addListener(() {
      _queryPoi();
    });

    _layerNames.add(LayerNameEntity("星球地图", true));
    _layerNames.add(LayerNameEntity("Mapbox", false));
    _layerNames.add(LayerNameEntity("天地图", false));

    var alreadyLand = widget.data[Contract.ALREADY_LAND];
    if (alreadyLand != null) {
      var dynamicValue = jsonDecode(alreadyLand);
      dynamicValue.forEach((v) {
        print("emmmmmm:添加地块1");
        _allLands.add(LandInfoEntity.fromJson(v));
      });
    }
    var villageLand = widget.data[Contract.VILLAGE_ALL_LAND];
    if (villageLand != null) {
      var dynamicValue = jsonDecode(villageLand);
      dynamicValue.forEach((v) {
        _allVillageLands.add(VillageLandEntity.fromJson(v));
      });
    }
    _confirmationName = widget.data[Contract.CONFIRMATION_NAME] ?? "";
    _confirmationIdCard = widget.data[Contract.CONFIRMATION_ID_CARD] ?? "";
    _provinceCode = widget.data[Contract.PROVINCE_CODE] ?? "";
    _subscription = EventBusUtil.on<BackEntity>().listen((event) {
      if (_isSaveLand) {
        ToastUtil.showToast("正在保存地块，请稍等");
        return;
      }
      _back();
    });
    String? taskType = widget.data[Contract.TASK_TYPE];
    if (taskType == null) {
      _taskType = TaskType.PLANT;
    } else {
      if (taskType == TaskType.FARM.name) {
        _taskType = TaskType.FARM;
      } else {
        _taskType = TaskType.PLANT;
      }
    }
    if (_allVillageLands.isEmpty) {
      return;
    }
    Set<String> years = {};
    Set<String> crops = {};
    for (var villageLand in _allVillageLands) {
      years.add(villageLand.time!);
      crops.add(villageLand.insurance!);
      if (villageLand.flag!) {
        _canCalVillageLands.add(villageLand);
      }
    }
    for (var element in years) {
      _yearListSelect.add(SelectEntity(name: element, isSelect: false));
    }

    for (var element in crops) {
      _cropListSelect.add(SelectEntity(name: element, isSelect: true));
    }

    _yearListSelect.sort((o1, o2) {
      return o1.name.compareTo(o2.name);
    });
    _yearListSelect[0].isSelect = true;
  }

  @override
  Widget build(BuildContext context) {
    return Stack(
      children: [
        BaseDrawMapView(
          isStartLocation: true,
          mapLoadSuccess: (drawLandManager) {
            _drawLandManager = drawLandManager;
            _mapBoxControl = _drawLandManager?.control;
            _setSelectVillage();
            _draw();
          },
          onMapTapListener: (coordinate) {
            Position position = Position(coordinate.y, coordinate.x);
            _queryMapFeature(position);
          },
          onMapLongTapListener: (coordinate) {
            Position position = Position(coordinate.y, coordinate.x);
            _queryMapLongFeature(position);
          },
          onMapMove: () {},
          onMapScrollListener: (coordinate) {
            int now = DateTime.now().millisecondsSinceEpoch;
            if ((lastTime - now).abs() > 500) {
              DrawLandWebSocketListener.endMove(coordinate);
            }
            lastTime = now;
          },
        ),
        visibility.Visibility(
            visible: !_isScreenshot,
            child: Stack(
              children: [
                _searchWidget(),
                _switchLayersWidget(),
                _switchLandWidget(),
                _bottomRightControl(),
                _centerWidget(),
                _bottomWidget(),
                _bottomControl(),
              ],
            ))
      ],
    );
  }

  // 底部控制内容
  Widget _bottomControl() {
    return visibility.Visibility(
      visible: _isShowControl,
      child: Positioned(
        left: 10.w,
        right: 10.w,
        bottom: 100.w,
        child: Center(
          child: SizedBox(
            width: 100.w,
            height: 100.w,
            child: Stack(
              children: [
                Align(
                  alignment: Alignment.topCenter,
                  child: InkWell(
                    onTap: () async {
                      _drawLandManager?.drawLand?.top();
                    },
                    child: Container(
                      width: 40.w,
                      height: 40.w,
                      decoration: BoxDecoration(
                          color: Colors.white,
                          borderRadius: BorderRadius.circular(20.w)),
                      child: Icon(
                        Icons.keyboard_arrow_up,
                        size: 40.w,
                      ),
                    ),
                  ),
                ),
                Align(
                  alignment: Alignment.bottomCenter,
                  child: InkWell(
                    onTap: () async {
                      _drawLandManager?.drawLand?.bottom();
                    },
                    child: Container(
                      width: 40.w,
                      height: 40.w,
                      decoration: BoxDecoration(
                          color: Colors.white,
                          borderRadius: BorderRadius.circular(20.w)),
                      child: Icon(
                        Icons.keyboard_arrow_down,
                        size: 40.w,
                      ),
                    ),
                  ),
                ),
                Align(
                  alignment: Alignment.centerLeft,
                  child: InkWell(
                    onTap: () async {
                      _drawLandManager?.drawLand?.left();
                    },
                    child: Container(
                      width: 40.w,
                      height: 40.w,
                      decoration: BoxDecoration(
                          color: Colors.white,
                          borderRadius: BorderRadius.circular(20.w)),
                      child: Icon(
                        Icons.keyboard_arrow_left,
                        size: 40.w,
                      ),
                    ),
                  ),
                ),
                Align(
                  alignment: Alignment.centerRight,
                  child: InkWell(
                    onTap: () async {
                      _drawLandManager?.drawLand?.right();
                    },
                    child: Container(
                      width: 40.w,
                      height: 40.w,
                      decoration: BoxDecoration(
                          color: Colors.white,
                          borderRadius: BorderRadius.circular(20.w)),
                      child: Icon(
                        Icons.keyboard_arrow_right,
                        size: 40.w,
                      ),
                    ),
                  ),
                ),
              ],
            ),
          ),
        ),
      ),
    );
  }

  // 底部操作类型
  Widget _bottomWidget() {
    return Positioned(
      left: 10.w,
      right: 10.w,
      bottom: 16.w,
      child: Column(
        children: [
          Row(
            children: [
              Expanded(
                child: SizedBox(
                  height: 30.w,
                ),
              ),
              SizedBox(
                width: 20.w,
              ),
              Expanded(
                child: visibility.Visibility(
                  visible: _isStartDraw,
                  child: InkWell(
                    onTap: () async {
                      var center = await _mapBoxControl?.getCenter();
                      if (center != null) {
                        _drawLandManager?.addPoint(center.coordinates);
                      }
                    },
                    child: Container(
                      height: 30.w,
                      decoration: BoxDecoration(
                          color: const Color(0xFF5A8DDF),
                          borderRadius:
                              BorderRadius.all(Radius.circular(10.w))),
                      child: Center(
                        child: Text(
                          '打点',
                          style:
                              TextStyle(color: Colors.white, fontSize: 16.sp),
                        ),
                      ),
                    ),
                  ),
                ),
              ),
              SizedBox(
                width: 20.w,
              ),
              Expanded(
                child: SizedBox(
                  height: 30.w,
                ),
              ),
            ],
          ),
          SizedBox(
            height: 10.w,
          ),
          Row(
            children: [
              Expanded(
                child: visibility.Visibility(
                  visible: _isStartDraw,
                  child: InkWell(
                    onTap: () {
                      _drawLandManager?.undo();
                    },
                    child: Container(
                      height: 30.w,
                      decoration: BoxDecoration(
                          color: Colors.white,
                          borderRadius:
                              BorderRadius.all(Radius.circular(10.w))),
                      child: Center(
                        child: Text(
                          '撤销',
                          style:
                              TextStyle(color: Colors.black, fontSize: 16.sp),
                        ),
                      ),
                    ),
                  ),
                ),
              ),
              SizedBox(
                width: 20.w,
              ),
              Expanded(
                child: InkWell(
                  onTap: () {
                    if (!_isStartDraw) {
                      if (directDraw) {
                        _drawLandManager?.startDraw(DrawType.DRAW_LAND);
                        _isStartDraw = true;
                        _landInfoEntity =
                            LandInfoEntity(landName: "", state: 3);
                        setState(() {});
                        return;
                      }
                      LandInfoEntity landInfoEntity = LandInfoEntity(
                          userName: _confirmationName,
                          idCard: _confirmationIdCard,
                          state: 3);
                      showLandInfoCompleteDialog(
                          context: context,
                          landInfoEntity: landInfoEntity,
                          provinceCode: _provinceCode,
                          taskType: _taskType!,
                          submitDialog: (context, landInfo) {
                            Navigator.of(context).pop();
                            _landInfoEntity = landInfo;
                            _drawLandManager?.startDraw(DrawType.DRAW_LAND);
                            setState(() {
                              _isStartDraw = true;
                              DrawLandWebSocketListener.startDraw();
                            });
                          },
                          cancelDialog: (context) {
                            Navigator.of(context).pop();
                          });
                    } else {
                      showLandDrawQuitDialog(
                          context: context,
                          save: (context) {
                            if (_drawLandManager == null ||
                                _drawLandManager!.drawLand == null) {
                              return;
                            }
                            if (_drawLandManager!.drawLand!.positions.length <
                                3) {
                              ToastUtil.showToast("地块绘制的点数少于3个，不能完成");
                              return;
                            }
                            if (!_verifyLand()) {
                              return;
                            }
                            Navigator.of(context).pop();
                            _save(canVerify: false);
                          },
                          delete: (context) async {
                            Navigator.of(context).pop();
                            if (_landInfoEntity == null) {
                              return;
                            }
                            // 如果是新增的话，那么直接删除就行了，否则的话，就需要更改成删除状态
                            if (_landInfoEntity!.state == 3) {
                              _allLands.remove(_landInfoEntity);
                            } else {
                              _landInfoEntity!.state = 2;
                              print("emmmmmm:添加地块2");
                              _allLands.add(_landInfoEntity!);
                            }
                            await _drawLandManager?.delete();
                            await _draw();
                            setState(() {
                              _isStartDraw = false;
                              _isShowControl = false;
                              DrawLandWebSocketListener.exitDraw();
                            });
                          });
                    }
                  },
                  child: Container(
                    height: 30.w,
                    decoration: BoxDecoration(
                        color: const Color(0xFF5A8DDF),
                        borderRadius: BorderRadius.all(Radius.circular(10.w))),
                    child: Center(
                      child: Text(
                        _isStartDraw ? '退出圈地' : "开始圈地",
                        style: TextStyle(color: Colors.white, fontSize: 16.sp),
                      ),
                    ),
                  ),
                ),
              ),
              SizedBox(
                width: 20.w,
              ),
              Expanded(
                child: visibility.Visibility(
                  visible: _isStartDraw,
                  child: InkWell(
                    onTap: () {
                      if (_drawLandManager == null ||
                          _drawLandManager!.drawLand == null) {
                        return;
                      }
                      if (_drawLandManager!.drawLand!.positions.length < 3) {
                        ToastUtil.showToast("地块绘制的点数少于3个，不能完成");
                        return;
                      }
                      _save();
                    },
                    child: Container(
                      height: 30.w,
                      decoration: BoxDecoration(
                          color: const Color(0xFF5A8DDF),
                          borderRadius:
                              BorderRadius.all(Radius.circular(10.w))),
                      child: Center(
                        child: Text(
                          '保存',
                          style:
                              TextStyle(color: Colors.white, fontSize: 16.sp),
                        ),
                      ),
                    ),
                  ),
                ),
              ),
            ],
          )
        ],
      ),
    );
  }

  // 右下的控制部分
  Widget _bottomRightControl() {
    return Positioned(
      bottom: 80.w,
      right: 20.w,
      child: Column(
        children: [
          visibility.Visibility(
            visible: _isStartDraw,
            child: InkWell(
              onTap: () {
                setState(() {
                  _isShowControl = !_isShowControl;
                });
              },
              child: Container(
                padding: EdgeInsets.all(5.w),
                decoration: BoxDecoration(
                    color: Colors.white,
                    borderRadius: BorderRadius.circular(8.w)),
                child: Icon(
                  Icons.control_camera_outlined,
                  size: 24.w,
                  color: _isShowControl
                      ? const Color(0xFF5A8DDF)
                      : const Color(0xFF757575),
                ),
              ),
            ),
          ),
          SizedBox(
            height: 15.w,
          ),
          InkWell(
            onTap: () {
              setState(() {
                _isShowOverlap = !_isShowOverlap;
                _drawOverlap();
              });
            },
            child: Container(
              padding: EdgeInsets.all(5.w),
              decoration: BoxDecoration(
                  color: Colors.white,
                  borderRadius: BorderRadius.circular(8.w)),
              child: Image.asset(
                _isShowOverlap
                    ? "images/icon_show_overlap.jpg"
                    : "images/icon_hide_overlap.jpg",
                width: 24.w,
                height: 24.w,
                package: Contract.packageName,
              ),
            ),
          ),
          SizedBox(
            height: 15.w,
          ),
          InkWell(
            onTap: () {
              _mapBoxControl?.startLocation();
            },
            child: Container(
              padding: EdgeInsets.all(5.w),
              decoration: BoxDecoration(
                  color: Colors.white,
                  borderRadius: BorderRadius.circular(8.w)),
              child: Icon(Icons.my_location_sharp,
                  size: 24.w, color: const Color(0xFF333333)),
            ),
          ),
          SizedBox(
            height: 15.w,
          ),
          InkWell(
            onTap: () {
              setState(() {
                _isShowFour = !_isShowFour;
                _drawAllLandFour();
              });
            },
            child: Container(
              padding: EdgeInsets.all(5.w),
              decoration: BoxDecoration(
                  color: Colors.white,
                  borderRadius: BorderRadius.circular(8.w)),
              child: Image.asset(
                _isShowFour
                    ? "images/map_four_on.png"
                    : "images/map_four_off.png",
                width: 24.w,
                height: 24.w,
                package: Contract.packageName,
              ),
            ),
          ),
        ],
      ),
    );
  }

  // 中心坐标
  Widget _centerWidget() {
    return Positioned(
      top: 0,
      bottom: 0,
      right: 0,
      left: 0,
      child: Icon(
        Icons.add,
        color: Colors.red,
        size: 40.w,
      ),
    );
  }

  // 切换历史地块的显隐
  Widget _switchLandWidget() {
    return Positioned(
      right: 20.w,
      top: 140.w,
      child: Row(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          visibility.Visibility(
            visible: _isSwitchLand,
            child: Container(
              padding: EdgeInsets.all(8.w),
              decoration: BoxDecoration(
                color: Colors.white,
                borderRadius: BorderRadius.circular(5.w),
              ),
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  Row(
                    children: [
                      Container(
                        color: const Color(0xFF5A8DDF),
                        width: 3.w,
                        height: 16.w,
                      ),
                      SizedBox(
                        width: 3.w,
                      ),
                      Text(
                        "地块",
                        style:
                            TextStyle(fontSize: 16.sp, color: Colors.black38),
                      )
                    ],
                  ),
                  Column(
                    children: _yearListSelect.map((year) {
                      return InkWell(
                        onTap: () {
                          setState(() {
                            year.isSelect = !year.isSelect;
                            _setSelectVillage();
                          });
                        },
                        child: Row(
                          children: [
                            Checkbox(
                                value: year.isSelect,
                                onChanged: (value) {
                                  setState(() {
                                    year.isSelect = !year.isSelect;
                                    _setSelectVillage();
                                  });
                                }),
                            Text(
                              year.name,
                              style: TextStyle(
                                  fontSize: 16.sp, color: Colors.black38),
                            )
                          ],
                        ),
                      );
                    }).toList(),
                  ),
                  Row(
                    children: [
                      Container(
                        color: const Color(0xFF5A8DDF),
                        width: 3.w,
                        height: 16.w,
                      ),
                      SizedBox(
                        width: 3.w,
                      ),
                      Text(
                        "作物分类",
                        style:
                            TextStyle(fontSize: 16.sp, color: Colors.black38),
                      )
                    ],
                  ),
                  Column(
                    children: _cropListSelect.map((crop) {
                      return InkWell(
                        onTap: () {
                          setState(() {
                            crop.isSelect = !crop.isSelect;
                            _setSelectVillage();
                          });
                        },
                        child: Row(
                          children: [
                            Checkbox(
                                value: crop.isSelect,
                                onChanged: (value) {
                                  setState(() {
                                    crop.isSelect = !crop.isSelect;
                                    _setSelectVillage();
                                  });
                                }),
                            Text(
                              crop.name,
                              style: TextStyle(
                                  fontSize: 16.sp, color: Colors.black38),
                            )
                          ],
                        ),
                      );
                    }).toList(),
                  ),
                ],
              ),
            ),
          ),
          SizedBox(
            width: 8.w,
          ),
          InkWell(
            onTap: () {
              setState(() {
                _isSwitchLand = !_isSwitchLand;
                _isShowSwitchLayers = false;
              });
            },
            child: Container(
              padding: EdgeInsets.all(5.w),
              decoration: BoxDecoration(
                  color: Colors.white,
                  borderRadius: BorderRadius.circular(8.w)),
              child: Icon(
                Icons.satellite_alt_outlined,
                size: 24.w,
                color: _isSwitchLand
                    ? const Color(0xFF5A8DDF)
                    : const Color(0xFF757575),
              ),
            ),
          ),
        ],
      ),
    );
  }

  // 图层切换widget
  Widget _switchLayersWidget() {
    return Positioned(
      right: 20.w,
      top: 80.w,
      child: Row(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          visibility.Visibility(
            visible: _isShowSwitchLayers,
            child: Container(
              padding: EdgeInsets.all(8.w),
              decoration: BoxDecoration(
                color: Colors.white,
                borderRadius: BorderRadius.circular(5.w),
              ),
              child: Column(
                children: _layerNames.map((layerName) {
                  return InkWell(
                    onTap: () {
                      setState(() {
                        for (var element in _layerNames) {
                          element.isSelect = false;
                        }
                        layerName.isSelect = true;
                        ShowType showType = ShowType.XINGTU;
                        if ("星球地图" == layerName.name) {
                          showType = ShowType.XINGTU;
                        } else if ("Mapbox" == layerName.name) {
                          showType = ShowType.MAPBOX;
                        } else {
                          showType = ShowType.TDT;
                        }
                        _drawLandManager?.switchLayer(showType);
                      });
                    },
                    child: Container(
                      padding: EdgeInsets.symmetric(vertical: 3.w),
                      child: Text(
                        layerName.name,
                        style: TextStyle(
                            color: layerName.isSelect
                                ? const Color(0xFF5A8DDF)
                                : const Color(0xFF333333),
                            fontSize: 16.sp),
                      ),
                    ),
                  );
                }).toList(),
              ),
            ),
          ),
          SizedBox(
            width: 8.w,
          ),
          InkWell(
            onTap: () {
              setState(() {
                _isShowSwitchLayers = !_isShowSwitchLayers;
                _isSwitchLand = false;
              });
            },
            child: Container(
              padding: EdgeInsets.all(5.w),
              decoration: BoxDecoration(
                  color: Colors.white,
                  borderRadius: BorderRadius.circular(8.w)),
              child: Icon(
                Icons.layers,
                size: 24.w,
                color: _isShowSwitchLayers
                    ? const Color(0xFF5A8DDF)
                    : const Color(0xFF757575),
              ),
            ),
          ),
        ],
      ),
    );
  }

  // 搜索部分的widget
  Widget _searchWidget() {
    return Column(
      children: [
        Container(
          height: 1.w,
          color: const Color(0xFFECECEC),
        ),
        Container(
          padding: EdgeInsets.symmetric(horizontal: 8.w),
          decoration: BoxDecoration(
              color: Colors.white,
              borderRadius: BorderRadius.only(
                  bottomLeft: Radius.circular(5.w),
                  bottomRight: Radius.circular(5.w))),
          child: TextField(
            controller: _textEditingController,
            style: TextStyle(color: Colors.black, fontSize: 14.sp),
            decoration: InputDecoration(
                border: InputBorder.none,
                hintText: "搜索地图位置",
                hintStyle: TextStyle(fontSize: 14.sp)),
          ),
        ),
        visibility.Visibility(
          visible: _isShowPoiSearch,
          child: Container(
            height: 300.w,
            decoration: BoxDecoration(
                color: Colors.white70,
                borderRadius: BorderRadius.circular(8.w)),
            margin: EdgeInsets.only(left: 8.w, right: 8.w, top: 10.w),
            padding: EdgeInsets.symmetric(horizontal: 10.w),
            child: ListView.builder(
              itemBuilder: (context, index) {
                var poi = _poiList[index];
                return InkWell(
                  onTap: () {
                    var latLng = poi.pointEntity!;
                    var cordResult = CoordTransform.transformGCJ02toWGS84(
                        latLng.longitude!, latLng.latitude!);
                    _mapBoxControl?.moveToCenter(
                        Position(cordResult.lon, cordResult.lat));
                    setState(() {
                      _isShowPoiSearch = false;
                      _poiList.clear();
                    });
                  },
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      SizedBox(
                        height: 6.w,
                      ),
                      Text(
                        poi.name.toString(),
                        style: TextStyle(color: Colors.black, fontSize: 14.sp),
                      ),
                      Text(
                        poi.cityname.toString() + poi.address.toString(),
                        style: TextStyle(color: Colors.black, fontSize: 14.sp),
                      ),
                      SizedBox(
                        height: 6.w,
                      ),
                    ],
                  ),
                );
              },
              itemCount: _poiList.length,
            ),
          ),
        )
      ],
    );
  }

  // 查询poi
  void _queryPoi() async {
    print('emmmmmmmm:_queryPoi');
    var text = _textEditingController.text;
    _poiList.clear();
    if (text.isNotEmpty) {
      var searchPoi = await AmapSearchUtil.searchPoi(text);
      if (text == _textEditingController.text) {
        _poiList.addAll(searchPoi);
        _isShowPoiSearch = true;
      } else {
        _isShowPoiSearch = false;
      }
    } else {
      _isShowPoiSearch = false;
    }
    setState(() {});
  }

  // 3千米限制的圆
  void _add3KilometersCircle(Position point) async {
    await _mapBoxControl?.removeLayerAndSource(
        _3K_BUFFER_LAYER, _3K_BUFFER_SOURCE);
    LineString lineString =
        LineString(coordinates: TurfGeometryUtil.getCircle(point, 3000));
    GeoJsonSource geoJsonSource = GeoJsonSource(
        id: _3K_BUFFER_SOURCE,
        data: jsonEncode(Feature(id: "", geometry: lineString).toJson()));
    await _mapBoxControl?.style.addSource(geoJsonSource);
    LineLayer lineLayer = LineLayer(
      id: _3K_BUFFER_LAYER,
      sourceId: _3K_BUFFER_SOURCE,
      lineColor: const Color(0xFF00FF00).value,
      lineWidth: 2.w,
    );
    await _mapBoxControl?.style.addLayer(lineLayer);
  }

  Future<void> _draw() async {
    await _drawAllLands();
    await _drawAllLandFour();
    await _drawOverlap();
  }

  // 显示覆盖率
  Future<void> _drawOverlap() async {
    await _mapBoxControl?.removeLayer(_OVERLAP_LINE_LAYER);
    await _mapBoxControl?.removeLayerAndSource(
        _OVERLAP_FILL_LAYER, _OVERLAP_SOURCE);
    await _mapBoxControl?.removeLayerAndSource(
        _OVERLAP_CENTER_LAYER, _OVERLAP_CENTER_SOURCE);
    if (!_isShowOverlap) {
      return;
    }
    if (_allLands.isEmpty) {
      return;
    }
    List<LandInfoEntity> canCalLands = [];
    for (var value in _allLands) {
      if (value.state != 2) {
        canCalLands.add(value);
      }
    }
    if (canCalLands.isEmpty) {
      return;
    }

    List<Feature> landFeatures = [];
    List<Feature> centerFeatures = [];
    for (int i = 0; i < canCalLands.length - 1; i++) {
      for (int j = i + 1; j < canCalLands.length; j++) {
        var path1 = canCalLands[i].path!;
        var path2 = canCalLands[j].path!;
        if (JtsGeometryUtil.isOverlaps(path1, path2)) {
          var overlapsPolygon =
              TurfGeometryUtil.getOverlapsPolygon(path1, path2);
          if (overlapsPolygon.isNotEmpty) {
            for (var value in overlapsPolygon) {
              if (value.isNotEmpty) {
                List<List<Position>> pointListList = [];
                pointListList.add(value);
                Polygon polygon = Polygon(coordinates: pointListList);
                landFeatures.add(Feature(id: "", geometry: polygon));
                double area = TurfGeometryUtil.calculateArea(value);
                Position center = JtsGeometryUtil.getGeometryCenter(value);
                Point point = Point(coordinates: center);
                Map<String, dynamic> properties = {};
                double overlap = area *
                    2 *
                    100 /
                    (TurfGeometryUtil.calculatePointArea(path1) +
                        TurfGeometryUtil.calculatePointArea(path2));
                properties["area"] =
                    "${NumberUtil.getValue(area / 666.67, 2)}亩\n重叠率${NumberUtil.getValue(overlap, 2)}%";
                centerFeatures.add(
                    Feature(id: "", geometry: point, properties: properties));
              }
            }
          }
        }
      }
    }

    for (var village in _canCalVillageLands) {
      for (var land in canCalLands) {
        var path1 = village.path!;
        var path2 = land.path!;
        if (JtsGeometryUtil.isOverlaps(path1, path2)) {
          var overlapsPolygon =
              TurfGeometryUtil.getOverlapsPolygon(path1, path2);
          if (overlapsPolygon.isNotEmpty) {
            for (var value in overlapsPolygon) {
              List<List<Position>> pointListList = [];
              pointListList.add(value);
              Polygon polygon = Polygon(coordinates: pointListList);
              landFeatures.add(Feature(id: "", geometry: polygon));
              double area = TurfGeometryUtil.calculateArea(value);
              Position center = JtsGeometryUtil.getGeometryCenter(value);
              Point point = Point(coordinates: center);
              Map<String, dynamic> properties = {};
              double overlap =
                  area * 100 / TurfGeometryUtil.calculatePointArea(path2);
              properties["area"] =
                  "${NumberUtil.getValue(area / 666.67, 2)}亩\n重叠率${NumberUtil.getValue(overlap, 2)}%";
              centerFeatures.add(
                  Feature(id: "", geometry: point, properties: properties));
            }
          }
        }
      }
    }
    if (landFeatures.isEmpty) {
      return;
    }
    GeoJsonSource polygonSource = GeoJsonSource(
        id: _OVERLAP_SOURCE,
        data: jsonEncode(FeatureCollection(features: landFeatures).toJson()));
    await _mapBoxControl?.style.addSource(polygonSource);
    FillLayer fillLayer = FillLayer(
        id: _OVERLAP_FILL_LAYER,
        sourceId: _OVERLAP_SOURCE,
        fillColor: Colors.blue.value,
        fillOpacity: 0.2);
    await _mapBoxControl?.style.addLayer(fillLayer);

    LineLayer lineLayer = LineLayer(
        id: _OVERLAP_LINE_LAYER,
        sourceId: _OVERLAP_SOURCE,
        lineColor: Colors.blue.value,
        lineWidth: 2.w);
    await _mapBoxControl?.style.addLayer(lineLayer);

    GeoJsonSource source = GeoJsonSource(
        id: _OVERLAP_CENTER_SOURCE,
        data: jsonEncode(FeatureCollection(features: centerFeatures).toJson()));
    await _mapBoxControl?.style.addSource(source);
    var layer = {
      "id": _OVERLAP_CENTER_LAYER,
      "source": _OVERLAP_CENTER_SOURCE,
      "type": "symbol",
      "layout": {"text-size": Contract.LAND_AREA_SIZE, 'text-field': '{area}'},
      "paint": {
        "text-color": "rgba(255, 255, 255, 255)",
      }
    };
    await _mapBoxControl?.style.addStyleLayer(json.encode(layer), null);
  }

  // 绘制所有地块
  Future<void> _drawAllLands() async {
    await _mapBoxControl?.removeLayer(_ALL_LAND_LINE_LAYER);
    await _mapBoxControl?.removeLayerAndSource(
        _ALL_LAND_FILL_LAYER, _ALL_LAND_SOURCE);
    await _mapBoxControl?.removeLayerAndSource(
        _ALL_LAND_CENTER_LAYER, _ALL_LAND_CENTER_SOURCE);
    if (_allLands.isEmpty) {
      return;
    }

    List<Feature> landFeatures = [];
    List<Feature> centerFeatures = [];
    for (var land in _allLands) {
      if (land.state == 2 || land.path == null) {
        continue;
      }
      var paths = land.path!;
      List<Position> pointList = [];
      for (var path in paths) {
        pointList.add(Position(path.longitude as num, path.latitude as num));
      }
      List<List<Position>> pointListList = [];
      pointListList.add(pointList);
      Polygon polygon = Polygon(coordinates: pointListList);
      Map<String, dynamic> landProperties = {};
      landProperties["uuid"] = land.uuid;
      landFeatures
          .add(Feature(id: "", geometry: polygon, properties: landProperties));

      double area = TurfGeometryUtil.calculateArea(pointList);
      Position center = JtsGeometryUtil.getGeometryCenter(pointList);
      Point point = Point(coordinates: center);
      Map<String, dynamic> properties = {};
      properties["area"] = "地块面积：\n${NumberUtil.getValue(area / 666.67, 2)}亩";
      centerFeatures
          .add(Feature(id: "", geometry: point, properties: properties));
    }
    if (landFeatures.isEmpty) {
      return;
    }
    GeoJsonSource polygonSource = GeoJsonSource(
        id: _ALL_LAND_SOURCE,
        data: jsonEncode(FeatureCollection(features: landFeatures).toJson()));
    await _mapBoxControl?.style.addSource(polygonSource);
    FillLayer fillLayer = FillLayer(
        id: _ALL_LAND_FILL_LAYER,
        sourceId: _ALL_LAND_SOURCE,
        fillColor: Colors.red.value,
        fillOpacity: 0.2);
    await _mapBoxControl?.style.addLayer(fillLayer);

    LineLayer lineLayer = LineLayer(
        id: _ALL_LAND_LINE_LAYER,
        sourceId: _ALL_LAND_SOURCE,
        lineColor: Colors.red.value,
        lineWidth: 2.w);
    await _mapBoxControl?.style.addLayer(lineLayer);

    GeoJsonSource source = GeoJsonSource(
        id: _ALL_LAND_CENTER_SOURCE,
        data: jsonEncode(FeatureCollection(features: centerFeatures).toJson()));
    await _mapBoxControl?.style.addSource(source);
    var layer = {
      "id": _ALL_LAND_CENTER_LAYER,
      "source": _ALL_LAND_CENTER_SOURCE,
      "type": "symbol",
      "layout": {"text-size": Contract.LAND_AREA_SIZE, 'text-field': '{area}'},
      "paint": {
        "text-color": "rgba(0, 0, 0, 255)",
        "text-halo-blur": 1.0,
        "text-halo-color": "rgba(255, 255, 255, 255)",
        "text-halo-width": 2.w
      }
    };
    await _mapBoxControl?.style.addStyleLayer(json.encode(layer), null);
  }

  // 绘制四至
  Future<void> _drawAllLandFour() async {
    await _mapBoxControl?.removeLayerAndSource(
        _LAND_FOUR_LINE_LAYER, _LAND_FOUR_LINE_SOURCE);
    await _mapBoxControl?.removeLayerAndSource(
        _LAND_FOUR_POINT_LAYER, _LAND_FOUR_POINT_SOURCE);
    if (!_isShowFour) {
      return;
    }

    if (_allLands.isEmpty) {
      return;
    }

    List<Feature> lineFeatures = [];
    List<Feature> pointFeatures = [];
    for (var land in _allLands) {
      if (land.state == 2 || land.path == null) {
        continue;
      }
      var paths = land.path!;
      List<Position> pointList = [];
      for (var path in paths) {
        pointList.add(Position(path.longitude as num, path.latitude as num));
      }
      var positions = JtsGeometryUtil.getGeometryEnvelope(pointList);

      for (var position in positions) {
        Point point = Point(coordinates: position);
        Map<String, dynamic> properties = {};
        properties["value"] =
            "${NumberUtil.getValue(position.lng.toDouble(), 8)}\n${NumberUtil.getValue(position.lat.toDouble(), 8)}";
        pointFeatures
            .add(Feature(id: "", geometry: point, properties: properties));
      }
      LineString lineString = LineString(coordinates: positions);
      lineFeatures.add(Feature(id: "", geometry: lineString));
    }
    if (pointFeatures.isEmpty) {
      return;
    }

    GeoJsonSource lineGeoJsonSource = GeoJsonSource(
        id: _LAND_FOUR_LINE_SOURCE,
        data: jsonEncode(FeatureCollection(features: lineFeatures).toJson()));
    await _mapBoxControl?.style.addSource(lineGeoJsonSource);

    LineLayer lineLayer = LineLayer(
        id: _LAND_FOUR_LINE_LAYER,
        sourceId: _LAND_FOUR_LINE_SOURCE,
        lineColor: Colors.white.value,
        lineWidth: 2.w);
    await _mapBoxControl?.style.addLayer(lineLayer);

    GeoJsonSource source = GeoJsonSource(
        id: _LAND_FOUR_POINT_SOURCE,
        data: jsonEncode(FeatureCollection(features: pointFeatures).toJson()));
    await _mapBoxControl?.style.addSource(source);
    var layer = {
      "id": _LAND_FOUR_POINT_LAYER,
      "source": _LAND_FOUR_POINT_SOURCE,
      "type": "symbol",
      "layout": {"text-size": 12.w, 'text-field': '{value}'},
      "paint": {
        "text-color": "rgba(255, 255, 255, 255)",
      }
    };
    await _mapBoxControl?.style.addStyleLayer(json.encode(layer), null);
  }

  // 设置选中的village 地块
  void _setSelectVillage() async {
    for (var value in _allVillageLands) {
      value.isSelect = false;
    }
    var years = _yearListSelect.where((element) => element.isSelect);
    var crops = _cropListSelect.where((element) => element.isSelect);
    for (var villageLand in _allVillageLands) {
      for (var year in years) {
        for (var crop in crops) {
          if (villageLand.time == year.name &&
              villageLand.insurance == crop.name) {
            villageLand.isSelect = true;
          }
        }
      }
    }
    await _drawVillageLands();
  }

  // 显示该村已有的地块
  Future<void> _drawVillageLands() async {
    await _mapBoxControl?.removeLayer(_VILLAGE_LAND_LINE_LAYER);
    await _mapBoxControl?.removeLayerAndSource(
        _VILLAGE_LAND_FILL_LAYER, _VILLAGE_LAND_FILL_SOURCE);

    if (_allVillageLands.isEmpty) {
      return;
    }

    List<VillageLandEntity> landEntityList = [];
    for (var element in _allVillageLands) {
      if (element.isSelect!) {
        landEntityList.add(element);
      }
    }

    if (landEntityList.isEmpty) {
      return;
    }
    List<Feature> landFeatures = [];
    for (var villageLand in landEntityList) {
      if (villageLand.path == null) {
        break;
      }
      var paths = villageLand.path!;
      List<Position> pointList = [];
      for (var path in paths) {
        pointList.add(Position(path.longitude as num, path.latitude as num));
      }
      List<List<Position>> pointListList = [];
      pointListList.add(pointList);
      Polygon polygon = Polygon(coordinates: pointListList);
      Map<String, dynamic> properties = {};
      properties["uuid"] = villageLand.uuid;
      landFeatures
          .add(Feature(id: "", geometry: polygon, properties: properties));
    }
    if (landFeatures.isEmpty) {
      return;
    }
    GeoJsonSource polygonSource = GeoJsonSource(
        id: _VILLAGE_LAND_FILL_SOURCE,
        data: jsonEncode(FeatureCollection(features: landFeatures).toJson()));
    await _mapBoxControl?.style.addSource(polygonSource);
    FillLayer fillLayer = FillLayer(
        id: _VILLAGE_LAND_FILL_LAYER,
        sourceId: _VILLAGE_LAND_FILL_SOURCE,
        fillColor: Colors.yellow.value,
        fillOpacity: 0.2);
    await _mapBoxControl?.style.addLayer(fillLayer);
    LineLayer lineLayer = LineLayer(
        id: _VILLAGE_LAND_LINE_LAYER,
        sourceId: _VILLAGE_LAND_FILL_SOURCE,
        lineColor: Colors.yellow.value,
        lineWidth: 2.w);
    await _mapBoxControl?.style.addLayer(lineLayer);
  }

  // 查询地图的Feature
  void _queryMapFeature(Position position) async {
    if (_mapBoxControl == null) {
      return;
    }
    var coordinate =
        await _mapBoxControl!.positionToScreen(position, isMapToQuery: true);
    RenderedQueryGeometry geometry = RenderedQueryGeometry(
        value: jsonEncode(coordinate.encode()), type: Type.SCREEN_COORDINATE);
    if (await _queryLandFeature(geometry)) {
      return;
    }
    _queryVillageFeature(geometry);
  }

  // 长按查询地图的Feature
  void _queryMapLongFeature(Position position) async {
    if (_mapBoxControl == null) {
      return;
    }
    var coordinate =
        await _mapBoxControl!.positionToScreen(position, isMapToQuery: true);
    RenderedQueryGeometry geometry = RenderedQueryGeometry(
        value: jsonEncode(coordinate.encode()), type: Type.SCREEN_COORDINATE);
    await _queryLandFeature(geometry, true);
  }

  // 查询地块信息
  Future<bool> _queryLandFeature(RenderedQueryGeometry geometry,
      [bool isLong = false]) async {
    RenderedQueryOptions landQuery =
        RenderedQueryOptions(layerIds: [_ALL_LAND_FILL_LAYER]);
    var landFeatures = await _mapBoxControl!.mapboxMap
        .queryRenderedFeatures(geometry, landQuery);
    if (landFeatures.isEmpty) {
      return false;
    }
    var feature = landFeatures[0];
    if (feature == null) {
      return false;
    }
    if (feature.feature["properties"] != null &&
        feature.feature["properties"] is Map<Object?, Object?>) {
      String uuid =
          (feature.feature["properties"] as Map<Object?, Object?>)["uuid"]
              .toString();
      for (var value in _allLands) {
        if (value.uuid == uuid) {
          if (isLong) {
            _longClickLand(value);
          } else {
            showLandInfoCompleteDialog(
                provinceCode: _provinceCode,
                context: context,
                landInfoEntity: value,
                taskType: _taskType!,
                submitDialog: (context, landInfo) {
                  double realArea =
                      TurfGeometryUtil.calculatePointArea(landInfo.path!);
                  if (realArea / 666.67 >
                      double.parse(landInfo.confirmationArea!) * 1.05) {
                    if (_taskType == TaskType.FARM) {
                      ToastUtil.showToast("勾画地块与饲养场所面积偏差过大，请调整");
                    } else {
                      ToastUtil.showToast("勾画地块与承保面积偏差过大，请调整");
                    }
                  } else {
                    Navigator.of(context).pop();
                    for (var info in _allLands) {
                      if (info.uuid == landInfo.uuid) {
                        _allLands.remove(info);
                        if (landInfo.state != 3) {
                          landInfo.state = 1;
                        }
                        _allLands.add(landInfo);
                        break;
                      }
                    }
                  }
                },
                cancelDialog: (context) {
                  Navigator.of(context).pop();
                });
          }
          return true;
        }
      }
    }
    return false;
  }

  // 地块长按操作
  void _longClickLand(LandInfoEntity landInfoEntity) {
    showLandOperateDialog(
        context: context,
        delete: (context) async {
          Navigator.of(context).pop();
          if (landInfoEntity.state == 3) {
            _allLands.remove(landInfoEntity);
          } else {
            landInfoEntity.state = 2;
          }
          await _draw();
        },
        edit: (context) async {
          Navigator.of(context).pop();
          _landInfoEntity = landInfoEntity;
          _allLands.remove(landInfoEntity);
          await _draw();

          var path = landInfoEntity.path;
          List<Position> positions = [];
          for (int i = 0; i < path!.length - 1; i++) {
            var pointEntity = path[i];
            positions.add(Position(
                pointEntity.longitude as num, pointEntity.latitude as num));
          }
          _drawLandManager?.startDraw(DrawType.DRAW_LAND);
          _drawLandManager?.drawLand?.setPosition(positions);
          setState(() {
            _isStartDraw = true;
          });
        });
  }

  // 查询该村已有的地块
  Future<bool> _queryVillageFeature(RenderedQueryGeometry geometry) async {
    RenderedQueryOptions villageQuery =
        RenderedQueryOptions(layerIds: [_VILLAGE_LAND_FILL_LAYER]);
    var villageFeatures = await _mapBoxControl!.mapboxMap
        .queryRenderedFeatures(geometry, villageQuery);
    if (villageFeatures.isEmpty) {
      return false;
    }
    var feature = villageFeatures[0];
    if (feature == null) {
      return false;
    }
    if (feature.feature["properties"] != null &&
        feature.feature["properties"] is Map<Object?, Object?>) {
      String uuid =
          (feature.feature["properties"] as Map<Object?, Object?>)["uuid"]
              .toString();
      for (var value in _allVillageLands) {
        if (value.uuid == uuid) {
          showVillageLandInfoDialog(villageLandEntity: value, context: context);
          return true;
        }
      }
    }
    return false;
  }

  // 地块保存
  void _save({bool canVerify = true}) async {
    if (canVerify) {
      if (!_verifyLand()) {
        return;
      }
    }
    _isSaveLand = true;
    List<Position> positions = [];
    positions.addAll(_drawLandManager!.drawLand!.positions);
    positions.add(positions[0]);
    List<PointEntity> pointEntitys = [];
    for (var value in positions) {
      pointEntitys.add(PointEntity(
          longitude: value.lng.toDouble(), latitude: value.lat.toDouble()));
    }

    _landInfoEntity!.realityArea =
        (TurfGeometryUtil.calculateArea(positions) / 666.67).toString();
    _landInfoEntity!.perimeter =
        TurfGeometryUtil.calculateLength(positions).toString();
    List<PointEntity> path = [];
    for (var position in positions) {
      path.add(PointEntity(
          longitude: position.lng.toDouble(),
          latitude: position.lat.toDouble()));
    }
    _landInfoEntity!.path = path;
    Position center = JtsGeometryUtil.getGeometryCenter(positions);
    _landInfoEntity!.center = PointEntity(
        longitude: center.lng.toDouble(), latitude: center.lat.toDouble());
    if (_landInfoEntity!.state != 3) {
      _landInfoEntity!.state = 1;
    }

    await _drawLandManager?.delete();

    // 把地块画出来
    await _drawScreenShot(positions);

    setState(() {
      _isStartDraw = false;
      _isShowControl = false;
    });

    var envelop = JtsGeometryUtil.getEnvelope(positions);

    var cameraState = await _mapBoxControl?.mapboxMap.getCameraState();
    var cameraOptions = await _mapBoxControl?.mapboxMap
        .cameraForCoordinateBounds(
            CoordinateBounds(
                southwest: Point(
                        coordinates:
                            Position(envelop.getMaxX(), envelop.getMaxY()))
                    .toJson(),
                northeast: Point(
                        coordinates:
                            Position(envelop.getMinX(), envelop.getMinY()))
                    .toJson(),
                infiniteBounds: true),
            MbxEdgeInsets(top: 20.w, left: 20.w, right: 20.w, bottom: 20.w),
            cameraState!.bearing,
            cameraState.pitch);
    await _mapBoxControl?.mapboxMap
        .flyTo(cameraOptions!, MapAnimationOptions(duration: 20));

    // 开始截图
    setState(() {
      _isScreenshot = true;
    });

    // 截图
    await _screenShot();
    // 截图完之后开始恢复
    await _removeScreenShotLayer();
    _allLands.add(_landInfoEntity!);
    _landInfoEntity = null;
    await _draw();
    _isSaveLand = false;
    DrawLandWebSocketListener.exitDraw();
  }

  // 绘制截图部分的layer
  Future<void> _drawScreenShot(List<Position> positions) async {
    List<List<Position>> pointListList = [];
    pointListList.add(positions);
    Polygon polygon = Polygon(coordinates: pointListList);
    Feature<Polygon> polygonFeature = Feature(id: "", geometry: polygon);

    GeoJsonSource polygonSource = GeoJsonSource(
        id: _SNAPSHOT_LAND_SOURCE, data: jsonEncode(polygonFeature.toJson()));
    await _mapBoxControl?.style.addSource(polygonSource);
    FillLayer fillLayer = FillLayer(
        id: _SNAPHOT_LAND_FILL_LAYER,
        sourceId: _SNAPSHOT_LAND_SOURCE,
        fillColor: Colors.green.value,
        fillOpacity: 0.4);
    await _mapBoxControl?.style.addLayer(fillLayer);

    LineLayer lineLayer = LineLayer(
        id: _SNAPHOT_LAND_LINE_LAYER,
        sourceId: _SNAPSHOT_LAND_SOURCE,
        lineColor: Colors.green.value,
        lineWidth: 2.w);
    await _mapBoxControl?.style.addLayer(lineLayer);
  }

  // 删除截图部分的layer
  Future<void> _removeScreenShotLayer() async {
    await _mapBoxControl?.removeLayer(_SNAPHOT_LAND_LINE_LAYER);
    await _mapBoxControl?.removeLayerAndSource(
        _SNAPHOT_LAND_FILL_LAYER, _SNAPSHOT_LAND_SOURCE);
  }

  // 截屏处理
  Future<void> _screenShot() async {
    await Future.delayed(const Duration(milliseconds: 100));
    String? imagePath = await FlutterNativeScreenshot.takeScreenshot();
    setState(() {
      _isScreenshot = false;
    });
    if (imagePath == null || imagePath.isEmpty) {
      return;
    }

    File imageFile = File(imagePath);
    var uint8list = await ImageClipUtil.cropImage(
        imageData: imageFile.readAsBytesSync(),
        top: ScreenUtil().statusBarHeight + AppBar().preferredSize.height);

    await imageFile.delete();
    final directory = await getApplicationDocumentsDirectory();
    File file = await File(
            '${directory.path}/${DateTime.now().microsecondsSinceEpoch}.png')
        .create();
    await file.writeAsBytes(uint8list);
    _landInfoEntity!.picUrl = file.path;
  }

  // 验证地块是否合规
  bool _verifyLand() {
    if (_drawLandManager == null || _drawLandManager!.drawLand == null) {
      return false;
    }
    if (_landInfoEntity == null) {
      return false;
    }
    List<Position> positions = [];
    positions.addAll(_drawLandManager!.drawLand!.positions);
    positions.add(positions[0]);
    List<PointEntity> pointEntitys = [];
    for (var value in positions) {
      pointEntitys.add(PointEntity(
          longitude: value.lng.toDouble(), latitude: value.lat.toDouble()));
    }
    if (!_landIsMatchRequire(pointEntitys)) {
      return false;
    }
    return true;
  }

  // 判断地块是否符合要求
  bool _landIsMatchRequire(List<PointEntity> positions) {
    if (!TurfGeometryUtil.isSimple(positions)) {
      ToastUtil.showToast("地块出现自相交");
      return false;
    }
    // 真实面积
    var realArea = TurfGeometryUtil.calculatePointArea(positions);
    for (var land in _allLands) {
      if (land.state != 2 && land.path != null) {
        double landArea = TurfGeometryUtil.calculatePointArea(land.path!);
        var overlapsPolygon =
            TurfGeometryUtil.getOverlapsPolygon(land.path!, positions);
        // 覆盖的面积
        double overArea = 0.0;
        if (overlapsPolygon.isNotEmpty) {
          for (var polygon in overlapsPolygon) {
            if (polygon.isNotEmpty) {
              overArea += TurfGeometryUtil.calculateArea(polygon);
            }
          }
        }
        if (overArea / landArea > 0.05) {
          ToastUtil.showToast("该地块与已勾画地块重叠，请调整");
          return false;
        }
        if (overArea / realArea > 0.05) {
          ToastUtil.showToast("该地块与已勾画地块重叠，请调整");
          return false;
        }
      }
    }

    for (var village in _canCalVillageLands) {
      if (village.path != null) {
        double villageArea = TurfGeometryUtil.calculatePointArea(village.path!);
        var overlapsPolygon =
            TurfGeometryUtil.getOverlapsPolygon(village.path!, positions);
        // 覆盖的面积
        double overArea = 0.0;
        if (overlapsPolygon.isNotEmpty) {
          for (var polygon in overlapsPolygon) {
            if (polygon.isNotEmpty) {
              overArea += TurfGeometryUtil.calculateArea(polygon);
            }
          }
        }
        if (overArea / villageArea > 0.05) {
          ToastUtil.showToast("地块重叠率超过5%，请修改地块");
          return false;
        }
        if (overArea / realArea > 0.05) {
          ToastUtil.showToast("地块重叠率超过5%，请修改地块");
          return false;
        }
      }
    }
    if (directDraw) {
      //如果直接绘制，就没有confirmationArea
      return true;
    }
    if (realArea / 666.67 >
        double.parse(_landInfoEntity!.confirmationArea!) * 1.05) {
      if (_taskType == TaskType.FARM) {
        ToastUtil.showToast("勾画地块与饲养场所面积偏差过大，请调整");
      } else {
        ToastUtil.showToast("勾画地块与承保面积偏差过大，请调整");
      }
      return false;
    }
    return true;
  }

  // 返回操作
  void _back() {
    if (_isStartDraw) {
      ToastUtil.showToast("地块正在勾画，不能退出");
      return;
    }
    Navigator.of(context).pop(jsonEncode(_allLands));
  }

  @override
  void dispose() {
    super.dispose();
    _textEditingController.dispose();
    _drawLandManager?.dispose();
    _amapLocationControl.dispose();
    _subscription.cancel();
  }
}
